package com.lm.jmh.example;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@BenchmarkMode(Mode.Throughput) // 测试吞吐量
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Group)
@Fork(0)
public class MultiThreadedBenchmark {

    private AtomicInteger atomicCounter = new AtomicInteger();
    private int normalCounter = 0;

    @Benchmark
    @Group("atomic")
    @GroupThreads(4)
    public int testAtomicIncrement() {
        return atomicCounter.incrementAndGet();
    }

    @Benchmark
    @Group("normal")
    @GroupThreads(4)
    public int testNormalIncrement() {
        return ++normalCounter; // 非线程安全
    }

    // 主方法，用于运行基准测试
    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(MultiThreadedBenchmark.class.getSimpleName())
                .build();
        new Runner(opt).run();
    }
}

